package com.zhanghe.study.thread.pool;

import java.util.concurrent.*;

/**
 * @author zh
 * @date 2022/1/7 11:20
 */
public class TestCompletionService {
    public static void main(String[] args) {

        try{
            ExecutorService executorService = Executors.newFixedThreadPool(2);

            ExecutorCompletionService<String> executorCompletionService = new ExecutorCompletionService<>(executorService);

            for (int i = 0; i < 10; i++) {
                executorCompletionService.submit(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        long sleep = (long) (Math.random() * 1000);
                        System.out.println("sleep=" + sleep + " " + Thread.currentThread().getName());
                        Thread.sleep(sleep);
                        return Thread.currentThread().getName() + " " + sleep;
                    }
                });
            }

            for (int i = 0; i < 10; i++) {
                System.out.println(executorCompletionService.take().get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }


}
